package com.fish.anne.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.fish.anne.service.MemberLevelManager;
import com.fish.anne.model.MemberLevel;
import com.fish.anne.webapp.action.BaseAction;

import java.util.List;

public class MemberLevelAction extends BaseAction implements Preparable {
    private MemberLevelManager memberLevelManager;
    private List memberLevels;
    private MemberLevel memberLevel;
    private Long  levelId;

    public void setMemberLevelManager(MemberLevelManager memberLevelManager) {
        this.memberLevelManager = memberLevelManager;
    }

    public List getMemberLevels() {
        return memberLevels;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String memberLevelId = getRequest().getParameter("memberLevel.levelId");
            if (memberLevelId != null && !memberLevelId.equals("")) {
                memberLevel = memberLevelManager.get(new Long(memberLevelId));
            }
        }
    }

    public String list() {
        memberLevels = memberLevelManager.getAll();
        return SUCCESS;
    }

    public void setLevelId(Long  levelId) {
        this. levelId =  levelId;
    }

    public MemberLevel getMemberLevel() {
        return memberLevel;
    }

    public void setMemberLevel(MemberLevel memberLevel) {
        this.memberLevel = memberLevel;
    }

    public String delete() {
        memberLevelManager.remove(memberLevel.getLevelId());
        saveMessage(getText("memberLevel.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (levelId != null) {
            memberLevel = memberLevelManager.get(levelId);
        } else {
            memberLevel = new MemberLevel();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (memberLevel.getLevelId() == null);

        memberLevelManager.save(memberLevel);

        String key = (isNew) ? "memberLevel.added" : "memberLevel.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}